using System.CommandLine;
using System.CommandLine.Invocation;
using Microsoft.Extensions.Logging;
using SumerCoreDevOps.ExecuteNodeApi.Services;
using System.Text.Json;

namespace SumerCoreDevOps.ExecuteNodeApi.Commands;

/// <summary>
/// 节点注册命令行工具
/// </summary>
public class RegisterCommand
{
    /// <summary>
    /// 创建注册命令
    /// </summary>
    public static Command CreateCommand()
    {
        var command = new Command("register", "使用令牌注册节点到控制面板");

        // 添加选项
        var serverOption = new Option<string>(
            aliases: new[] { "--server", "-s" },
            description: "控制面板地址（格式: host:port）"
        ) { IsRequired = true };

        var tokenOption = new Option<string>(
            aliases: new[] { "--token", "-t" },
            description: "建立连接令牌（Join Token）"
        ) { IsRequired = true };

        var nameOption = new Option<string>(
            aliases: new[] { "--name", "-n" },
            description: "节点名称（可选）",
            getDefaultValue: () => Environment.MachineName
        );

        command.AddOption(serverOption);
        command.AddOption(tokenOption);
        command.AddOption(nameOption);

        command.SetHandler(async (server, token, name) =>
        {
            await ExecuteRegisterAsync(server, token, name);
        }, serverOption, tokenOption, nameOption);

        return command;
    }

    /// <summary>
    /// 执行注册
    /// </summary>
    private static async Task ExecuteRegisterAsync(string server, string token, string name)
    {
        try
        {
            Console.WriteLine("=== SumerCore DevOps 节点注册 ===");
            Console.WriteLine($"控制面板: {server}");
            Console.WriteLine($"节点名称: {name}");
            Console.WriteLine($"令牌: {MaskToken(token)}");
            Console.WriteLine();

            // 解析服务器地址
            var parts = server.Split(':');
            if (parts.Length != 2 || !int.TryParse(parts[1], out var port))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("❌ 错误: 服务器地址格式不正确，应为 host:port");
                Console.ResetColor();
                Environment.Exit(1);
                return;
            }

            var host = parts[0];

            // 更新 appsettings.json
            Console.WriteLine("📝 正在更新配置文件...");
            await UpdateAppSettingsAsync(host, port, token, name);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("✅ 配置已更新");
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("📌 提示：请使用以下命令启动节点服务：");
            Console.WriteLine("   dotnet run");
            Console.WriteLine();
            Console.WriteLine("或者");
            Console.WriteLine();
            Console.WriteLine("   systemctl start sumer-execute-node");
        }
        catch (Exception ex)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"❌ 注册失败: {ex.Message}");
            Console.ResetColor();
            Environment.Exit(1);
        }
    }

    /// <summary>
    /// 更新 appsettings.json
    /// </summary>
    private static async Task UpdateAppSettingsAsync(string host, int port, string token, string name)
    {
        var configPath = Path.Combine(AppContext.BaseDirectory, "appsettings.json");

        // 读取现有配置
        string jsonContent;
        JsonDocument existingConfig;

        if (File.Exists(configPath))
        {
            jsonContent = await File.ReadAllTextAsync(configPath);
            existingConfig = JsonDocument.Parse(jsonContent);
        }
        else
        {
            jsonContent = "{}";
            existingConfig = JsonDocument.Parse(jsonContent);
        }

        // 构建新配置
        var config = new
        {
            Logging = existingConfig.RootElement.TryGetProperty("Logging", out var logging)
                ? JsonSerializer.Deserialize<object>(logging.GetRawText())
                : new
                {
                    LogLevel = new
                    {
                        Default = "Information",
                        Microsoft = "Warning"
                    }
                },
            AllowedHosts = "*",
            Server = new
            {
                Host = host,
                Port = port,
                JoinToken = token
            },
            Node = new
            {
                Name = name,
                Key = "",
                Environments = new[] { "docker", "kubernetes", "dotnet" }
            }
        };

        // 写入配置文件
        var options = new JsonSerializerOptions
        {
            WriteIndented = true
        };

        var newJsonContent = JsonSerializer.Serialize(config, options);
        await File.WriteAllTextAsync(configPath, newJsonContent);
    }

    /// <summary>
    /// 遮蔽令牌显示
    /// </summary>
    private static string MaskToken(string token)
    {
        if (string.IsNullOrEmpty(token) || token.Length < 12)
            return "***";

        return $"{token.Substring(0, 6)}...{token.Substring(token.Length - 6)}";
    }
}
